package net.xumf.service.master.impl;

import net.xumf.service.master.MailService;
import net.xumf.support.model.bo.EmailBO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void sendText(EmailBO emailBO) {

        SimpleMailMessage message = new SimpleMailMessage();
        if (!StringUtils.isEmpty(emailBO.getSender())) {
            message.setFrom(emailBO.getSender());
        }
        message.setTo(emailBO.getReceiver());
        message.setSubject(emailBO.getTitle());
        message.setText(emailBO.getContent());
        javaMailSender.send(message);
    }

    @Override
    public void sendHtml(EmailBO emailBO) throws MessagingException {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setSubject(emailBO.getTitle());
        mimeMessageHelper.setTo(emailBO.getReceiver());
        if (!StringUtils.isEmpty(emailBO.getSender())) {
            mimeMessageHelper.setFrom(emailBO.getSender());
        }
        mimeMessageHelper.setText(emailBO.getContent(), true);

        javaMailSender.send(mimeMessage);
    }
}
